package com.wkbb.basic.controller.manage;

import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.Family;
import com.wkbb.basic.service.FamilyService;
import com.wkbb.basic.service.UserService;
import com.wkbb.basic.vo.FamilyManageEditVo;
import com.wkbb.basic.vo.FamilyManagePageListVo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.FamilyInfoDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.ExcelUtil;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.YearMonth;
import java.util.*;

/**
 * @author dengjingyuan
 * @date 2019-07-04 10:32
 */
@RestController
@Api(description = "家长管理(后台管理)")
@RequestMapping("/basic/{apiVersion}/family/manage")
@Slf4j
public class FamilyManageController extends BaseController {
    @Autowired
    private FamilyService familyService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "新增家长")
    @RequestMapping(value = "/addFamily", method = RequestMethod.POST)
    public ResultDTO addFamily(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @RequestBody FamilyManageEditVo familyManageEditVo) {
        log.info("***********FamilyManageController.addFamily******...apiVersion:{},Family:{}", apiVersion, familyManageEditVo);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        FamilyInfoDto familyInfoDto = familyManageEditVo.getFamilyInfoDto();
        List<StudentInfoDto> studentInfoDtoList = familyManageEditVo.getStudentInfoDtoList();
        if (familyInfoDto == null
                || StringUtil.isNullOrBlank(familyInfoDto.getName())
                || StringUtil.isNullOrBlank(familyInfoDto.getMobile())
                || studentInfoDtoList == null || studentInfoDtoList.isEmpty()) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            ErrorCode result = userService.checkMobileErrorCode(familyInfoDto.getMobile(), familyInfoDto.getCardNo(),
                    null, familyInfoDto.getUserId() == 0 ? null : familyInfoDto.getUserId(),
                    RoleTypeEnum.FAMILY.getValue(), familyInfoDto.getOrgId(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            familyService.insert(familyManageEditVo, userDto.getName(),true);

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********FamilyManageController.addFamily******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "修改家长")
    @RequestMapping(value = "/updateFamily", method = RequestMethod.PUT)
    public ResultDTO updateFamily(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @RequestBody FamilyInfoDto familyInfoDto) {
        log.info("***********FamilyManageController.updateFamily******...apiVersion:{},Family:{}", apiVersion, familyInfoDto);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (familyInfoDto == null || familyInfoDto.getId() == null || familyInfoDto.getId() == 0
//                || familyInfoDto.getUserId() == null || familyInfoDto.getUserId() == 0
//                || (familyInfoDto.getOrgId() == null || familyInfoDto.getOrgId() == 0)
//                || (familyInfoDto.getGradeId() == null || familyInfoDto.getGradeId() == 0)
//                || (familyInfoDto.getClassId() == null || familyInfoDto.getClassId() == 0)
//                || (familyInfoDto.getStudentUserId() == null || familyInfoDto.getStudentUserId() == 0)
//                || (familyInfoDto.getRelationType() == null || RelationTypeEnum.getDesc(familyInfoDto.getRelationType()) == null)
                || (familyInfoDto.getName() == null || familyInfoDto.getName().isEmpty())) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            //后台不会修改手机号，家长没有教工号
            ErrorCode result = userService.checkMobileErrorCode(null, familyInfoDto.getCardNo(),
                    null, familyInfoDto.getUserId(), RoleTypeEnum.FAMILY.getValue(), familyInfoDto.getOrgId(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            familyService.updateFamily(familyInfoDto, userDto.getName(), true);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********FamilyManageController.updateFamily******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除家长")
    @RequestMapping(value = "/deleteFamily", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteFamily(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "家长表id", defaultValue = "29", required = true) @RequestParam(name = "id", required = true) List<Long> ids) {
        log.info("***********FamilyManageController.deleteFamily******...apiVersion:{},ids:{}", apiVersion, Arrays.toString(ids.toArray()));

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return familyService.deleteFamily(ids, userDto.getName());
        } catch (Exception e) {
            log.error("***********FamilyManageController.deleteFamily******", e);
            return new ResultDTO<>(false);
        }
    }


    @ApiOperation(value = "查询家长详情")
    @RequestMapping(value = "/getFamilyInfoById", method = RequestMethod.GET)
    public ResultDTO<FamilyInfoDto> getFamilyInfoById(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "家长表id", defaultValue = "29", required = true) @RequestParam(name = "id", required = true) Long id) {
        log.info("***********FamilyManageController.getFamilyInfoById******...apiVersion:{},Employee:{}", apiVersion, id);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return new ResultDTO<>(familyService.getFamilyInfoById(id));
        } catch (Exception e) {
            log.error("***********FamilyManageController.getFamilyInfoById******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询家长分页列表")
    @RequestMapping(value = "/getFamilyInfoPageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<Family>> getFamilyInfoPageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
            @ApiParam(value = "学生姓名", required = false) @RequestParam(name = "studentName", required = false) String studentName,
            @ApiParam(value = "家长姓名", required = false) @RequestParam(name = "familyName", required = false) String familyName,
            @ApiParam(value = "家长手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "家长卡号", required = false) @RequestParam(name = "cardNo", required = false) String cardNo,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        log.info("***********FamilyManageController.getFamilyInfoPageList******...apiVersion:{}", apiVersion);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            HashMap<String, Object> params = new HashMap<>(7);
            if (null != orgId) {
                params.put("orgId", orgId);
            }
            if (null != gradeId) {
                params.put("gradeId", gradeId);
            }
            if (null != classId) {
                params.put("classId", classId);
            }
            if (!StringUtil.isNullOrBlank(studentName)) {
                params.put("studentName", studentName);
            }
            if (!StringUtil.isNullOrBlank(familyName)) {
                params.put("familyName", familyName);
            }
            if (!StringUtil.isNullOrBlank(mobile)) {
                params.put("mobile", mobile);
            }
            if (!StringUtil.isNullOrBlank(cardNo)) {
                params.put("cardNo", cardNo);
            }
//            return new ResultDTO<>(familyService.getFamilyManageList(params, pageNo, pageSize));
            return new ResultDTO<>(familyService.getFamilyListByPage(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********FamilyManageController.getFamilyInfoPageList:{}******", e.getMessage());
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "导出家长列表excel")
    @RequestMapping(value = "/exportFamilyInfoExcel", method = RequestMethod.GET)
    public ResultDTO exportFamilyInfoExcel(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
            @ApiParam(value = "学生姓名", required = false) @RequestParam(name = "studentName", required = false) String studentName,
            @ApiParam(value = "家长姓名", required = false) @RequestParam(name = "familyName", required = false) String familyName,
            @ApiParam(value = "家长手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "家长卡号", required = false) @RequestParam(name = "cardNo", required = false) String cardNo,
            @ApiParam(value = "登录token", required = false) @RequestParam(name = "token", required = false) String token,
            HttpServletResponse response)
    {

        log.info("***********FamilyManageController.exportFamilyInfoExcel******...apiVersion:{}", apiVersion);

        UserDto userDto = getUserByLogin(token);
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            HashMap<String, Object> params = new HashMap<>(7);
            if (null != orgId) {
                params.put("orgId", orgId);
            }
            if (null != gradeId) {
                params.put("gradeId", gradeId);
            }
            if (null != classId) {
                params.put("classId", classId);
            }
            if (!StringUtil.isNullOrBlank(studentName)) {
                params.put("studentName", studentName);
            }
            if (!StringUtil.isNullOrBlank(familyName)) {
                params.put("familyName", familyName);
            }
            if (!StringUtil.isNullOrBlank(mobile)) {
                params.put("mobile", mobile);
            }
            if (!StringUtil.isNullOrBlank(cardNo)) {
                params.put("cardNo", cardNo);
            }

            List<String> headers = new ArrayList<>();
            headers.add("学校名称");
            headers.add("家长姓名");
            headers.add("家长手机号");
            headers.add("家长卡号");
            headers.add("人脸照片");
            headers.add("人脸录入/修改时间");
            headers.add("关系");
            headers.add("学生姓名");
            headers.add("学生班级");

            String[] tempArray={};

            List<Object[]> dataList = familyService.exportFamilyExcel(params);
            if(org.apache.commons.collections.CollectionUtils.isEmpty(dataList)){
                return  new ResultDTO<>(ErrorCode.NOT_DATA);
            }

            String fileName = "家长"+ TimeUtil.toStringYYYY_MM_DD(new Date())+ "导出";
            ExcelUtil.exportAttendExcel("家长名单", fileName, headers.toArray(tempArray), dataList, response);
            return null;
        } catch (Exception e) {
            log.error("***********FamilyManageController.getFamilyInfoPageList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询全校家长列表（去重）")
    @RequestMapping(value = "/getFamilyListUnique", method = RequestMethod.GET)
    public ResultDTO<List<Family>> getFamilyListUnique(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId) {
        log.info("***********FamilyManageController.getFamilyListUnique******...apiVersion:{},orgId:{}", apiVersion, orgId);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return new ResultDTO<>(familyService.getFamilyListUniqueByOrgId(orgId));
        } catch (Exception e) {
            log.error("***********FamilyManageController.getFamilyListUnique******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "统计家长情况")
    @RequestMapping(value = "/statFamilyInfo", method = RequestMethod.GET)
    public ResultDTO statFamilyInfo(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId)
    {
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return new ResultDTO<>(familyService.statFamilyInfo(orgId,gradeId,classId));
        } catch (Exception e) {
            log.error("***********FamilyManageController.statFamilyInfo******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "家长人脸录入开关")
    @RequestMapping(value = "/operateFaceFlag", method = RequestMethod.POST)
    public ResultDTO<List<Family>> operateFaceFlag(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "家长ID", required = true) @RequestParam(name = "familyUserId", required = true) Long familyUserId,
            @ApiParam(value = "人脸录入开关(0关闭 1打开)", required = true) @RequestParam(name = "faceFlag", required = true) Boolean faceFlag) {
        log.info("***********FamilyManageController.operateFaceFlag******...orgId:{},familyId:{} faceFlag:{}",orgId,familyUserId,faceFlag);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            familyService.operateFaceFlag(orgId,familyUserId,faceFlag);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********FamilyManageController.operateFaceFlag******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "打开学校人脸配置同步家长人脸开关")
    @RequestMapping(value = "/syncFaceFlag", method = RequestMethod.POST)
    public ResultDTO<List<Family>> syncFaceFlag(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId) {
        log.info("***********FamilyManageController.syncFaceFlag******...orgId:{}",orgId);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if(null==orgId)
            {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            familyService.syncFaceFlag(orgId);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********FamilyManageController.syncFaceFlag******", e);
            return new ResultDTO<>(false);
        }
    }

}
